Page({
  data: {
    score: 0,
    bestScore: 0,
    gameStarted: false,
    gameOver: false
  },

  onLoad() {
    // 从缓存获取最高分
    const bestScore = wx.getStorageSync('flappyBirdBestScore') || 0;
    this.setData({ bestScore });
    
    this.initGame();
  },

  initGame() {
    this.ctx = wx.createCanvasContext('gameCanvas');
    
    // 游戏状态
    this.gameState = {
      bird: {
        x: 100,
        y: 300,
        width: 40,
        height: 30,
        velocity: 0,
        gravity: 0.5,
        jumpStrength: -8
      },
      pipes: [],
      gameSpeed: 3,
      pipeWidth: 60,
      pipeGap: 200, // 管道间隙
      pipeInterval: 1800, // 管道生成间隔(ms)
      lastPipeTime: 0,
      ground: {
        y: 750, // 地面位置
        height: 50
      }
    };

    this.gameRunning = false;
    this.animationFrame = null;
  },

  startGame() {
    this.setData({
      gameStarted: true,
      gameOver: false,
      score: 0
    });
    
    this.initGame();
    this.gameRunning = true;
    this.gameLoop(Date.now());
  },

  restartGame() {
    this.startGame();
  },

  onTap() {
    if (!this.gameRunning && this.data.gameStarted) {
      this.startGame();
      return;
    }
    
    if (this.gameRunning) {
      // 小鸟跳跃
      this.gameState.bird.velocity = this.gameState.bird.jumpStrength;
    }
  },

  gameLoop(timestamp) {
    if (!this.gameRunning) return;

    this.update(timestamp);
    this.render();
    
    this.animationFrame = setTimeout(() => {
      this.gameLoop(Date.now());
    }, 1000 / 60); // 60 FPS
  },

  update(timestamp) {
    const { bird, pipes, gameSpeed, pipeWidth, pipeGap, pipeInterval, ground } = this.gameState;

    // 更新小鸟位置
    bird.velocity += bird.gravity;
    bird.y += bird.velocity;

    // 生成新管道
    if (timestamp - this.gameState.lastPipeTime > pipeInterval) {
      this.generatePipe();
      this.gameState.lastPipeTime = timestamp;
    }

    // 更新管道位置
    for (let i = pipes.length - 1; i >= 0; i--) {
      pipes[i].x -= gameSpeed;

      // 移除屏幕外的管道
      if (pipes[i].x + pipeWidth < 0) {
        pipes.splice(i, 1);
        // 得分
        this.setData({ score: this.data.score + 1 });
      }
    }

    // 碰撞检测
    if (this.checkCollisions()) {
      this.endGame();
      return;
    }
  },

  generatePipe() {
    const minHeight = 50;
    const maxHeight = 400;
    const topHeight = Math.random() * (maxHeight - minHeight) + minHeight;
    
    this.gameState.pipes.push({
      x: 650, // 从右侧生成
      topHeight: topHeight,
      bottomY: topHeight + this.gameState.pipeGap
    });
  },

  checkCollisions() {
    const { bird, pipes, pipeWidth, ground } = this.gameState;

    // 碰到地面或天空
    if (bird.y <= 0 || bird.y + bird.height >= ground.y) {
      return true;
    }

    // 检测管道碰撞
    for (const pipe of pipes) {
      // 上管道碰撞
      if (bird.x < pipe.x + pipeWidth &&
          bird.x + bird.width > pipe.x &&
          bird.y < pipe.topHeight) {
        return true;
      }
      
      // 下管道碰撞
      if (bird.x < pipe.x + pipeWidth &&
          bird.x + bird.width > pipe.x &&
          bird.y + bird.height > pipe.bottomY) {
        return true;
      }
    }

    return false;
  },

  endGame() {
    this.gameRunning = false;
    this.setData({ gameOver: true });
    
    // 更新最高分
    if (this.data.score > this.data.bestScore) {
      this.setData({ bestScore: this.data.score });
      wx.setStorageSync('flappyBirdBestScore', this.data.score);
    }
    
    if (this.animationFrame) {
      clearTimeout(this.animationFrame);
    }
  },

  render() {
    const { bird, pipes, pipeWidth, ground } = this.gameState;
    const ctx = this.ctx;

    // 清空画布
    ctx.clearRect(0, 0, 650, 800);

    // 绘制背景
    ctx.fillStyle = '#87CEEB';
    ctx.fillRect(0, 0, 650, 800);

    // 绘制小鸟（黄色三角形）
    ctx.fillStyle = '#FFD700';
    ctx.beginPath();
    ctx.moveTo(bird.x, bird.y + bird.height / 2);
    ctx.lineTo(bird.x + bird.width, bird.y);
    ctx.lineTo(bird.x + bird.width, bird.y + bird.height);
    ctx.closePath();
    ctx.fill();

    // 绘制眼睛
    ctx.fillStyle = '#000';
    ctx.beginPath();
    ctx.arc(bird.x + 30, bird.y + 12, 4, 0, Math.PI * 2);
    ctx.fill();

    // 绘制管道
    ctx.fillStyle = '#228B22';
    pipes.forEach(pipe => {
      // 上管道
      ctx.fillRect(pipe.x, 0, pipeWidth, pipe.topHeight);
      // 下管道
      ctx.fillRect(pipe.x, pipe.bottomY, pipeWidth, 800 - pipe.bottomY);
    });

    // 绘制地面
    ctx.fillStyle = '#8B4513';
    ctx.fillRect(0, ground.y, 650, ground.height);

    // 绘制草地
    ctx.fillStyle = '#7CFC00';
    ctx.fillRect(0, ground.y, 650, 10);

    ctx.draw();
  },

  onUnload() {
    // 清理资源
    if (this.animationFrame) {
      clearTimeout(this.animationFrame);
    }
    this.gameRunning = false;
  }
});